package com.grm.service.impl;

import com.grm.async.SuanFaAsyncTask;
import com.grm.entity.DataExplore;
import com.grm.service.DataExploreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class DataExploreServiceImpl implements DataExploreService {
    private static final Integer EVERY_THREAD_EXECUTE_COUNT = 500;

    @Autowired
    private SuanFaAsyncTask suanFaAsyncTask;

    @Override
    public void executeDataExplore() {
        List<DataExplore> list = getDataExplores();

        // 1.创建线程池
        ExecutorService threadPool = new ThreadPoolExecutor(20, Integer.MAX_VALUE, 1, TimeUnit.DAYS,new LinkedBlockingQueue<Runnable>());

        int f= 0;
        int i= 0;
        //2.分发线程
        while (true){
            f = f+1;
            int g = (i+EVERY_THREAD_EXECUTE_COUNT) > list.size() ? list.size() : (i+EVERY_THREAD_EXECUTE_COUNT);
            List<DataExplore> childList = list.subList(i, g);
            if(!threadPool.isShutdown()){
                threadPool.execute(executeSuanFas(childList));
            }
            i= g;
            if(i>=list.size()){
                break;
            }
        }
        // 关闭线程池
        threadPool.shutdownNow();
    }

    /**
     * 线程池中使用异步方法调用
     * @param childList
     * @return
     */
    private Runnable executeSuanFas(List<DataExplore> childList) {
        return () -> {
            for (DataExplore dataExplore:childList) {
                suanFaAsyncTask.executeSuanFaA(dataExplore);
                suanFaAsyncTask.executeSuanFaB(dataExplore);
                suanFaAsyncTask.executeSuanFaC(dataExplore);
            }
        };
    }

    /**
     * 造假数据
     */
    private List<DataExplore> getDataExplores(){
        List<DataExplore> list = new ArrayList<>();
        for (int i = 0; i < 10000; i++) {
            DataExplore dataExplore = new DataExplore();
            dataExplore.setId(i+1);
            dataExplore.setName("dataExplore"+(i+1));
            list.add(dataExplore);
        }
        return list;
    }
}

